package com.bbs.controller;

import com.bbs.entity.Post;
import com.bbs.entity.User;
import com.bbs.service.PostService;
import com.bbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private PostService postService;



    /**
     * 个人主页
     * @return
     */
    @RequestMapping("/toMyProfile")
    public String toMyProfile(HttpSession session, Model model){
        int sessionUid = (int) session.getAttribute("uid");
        System.out.println(sessionUid);
        User user = userService.findById(sessionUid);
        List<Post> postList = postService.getPostList(sessionUid);
        model.addAttribute("user",user);
        model.addAttribute("postList",postList);
        return "myProfile";
    }


    /**
     *编辑个人信息
     *编写个人信息
     */
    @RequestMapping("/toEditProfile")
    public String toEditProfile(HttpSession session, Model model){
        int uid = (int) session.getAttribute("uid");
        User user = userService.findById(uid);
        model.addAttribute("user",user);
        return "editProfile";
    }

    /**
     *更新个人信息
     *
     */
    @RequestMapping("/editProfile")
    public String editProfile(User user){
        System.out.println(user);
        userService.updateUser(user);
        return "redirect:toMyProfile";
    }

    /**
     *查看他人主页信息
     *
     */
    @RequestMapping("/toProfile")
    public String toProfile(int uid,Model model,HttpSession session){
        //如果是自己的页面，直接跳转的本人的个人主页
        Integer sessionUid = (Integer)session.getAttribute("uid");
        if (sessionUid !=null && sessionUid==uid){
            return "redirect:toMyProfile";
        }
//判断是否关注当前用户

//        获得当前用户信息
        User user = userService.findById(uid);
//        获得发帖列表
        List<Post> postList = postService.getPostList(uid);
//像模型中添加数据
        model.addAttribute("following",false);
        model.addAttribute("user",user);
        model.addAttribute("postList",postList);
        return "profile";
    }
}
